//
//  LoginViewController.swift
//  DSHCMerchant
//
//  Created by 罗德良 on 2018/4/14.
//  Copyright © 2018年 袋鼠好车. All rights reserved.
//

import UIKit
import Alamofire
import HandyJSON

class LoginViewController: BaseViewController {
    @IBOutlet var userHeaderView: UIImageView!
    
    @IBOutlet var phoneTF: UITextField!

    @IBOutlet var passwordTF: UITextField!
    
    @IBOutlet var loginBtn: UIButton!
    
    var userModel: UserModel?
    
    var tapCount = 0
    
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.isNavigationBarHidden = true
        //测试崩溃
//        let arry:NSArray = ["1"]
//        print("%@",arry[5])
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.loginBtn.roundCorner(radius: 5)
        let tokenStr = UserDefaults.standard.value(forKey: "Token")
        if (tokenStr != nil) {
            //自动登录接口
            SVProgressHUD.show()
            Thread.sleep(forTimeInterval: 1.8)
            requstAutoLogin(token: tokenStr as! String)
        }
    }
    
    func configView() -> Void {
        
    }
    
    @IBAction func login(_ sender: UIButton) {
        SVProgressHUD.show()
        requstLogin(phone: self.phoneTF.text!, password: self.passwordTF.text!)
    }
    
    @IBAction func findPwdBtnPress(_ sender: UIButton) {
        let findpwdVC = FindPwdViewController();
        findpwdVC.title = "找回密码"; self.navigationController?.pushViewController(findpwdVC, animated: true)
    }
    
    
    @IBAction func regiserBtnPress(_ sender: UIButton) {
        let registerVC = RegisterViewController();
        registerVC.title = "注册"; self.navigationController?.pushViewController(registerVC, animated: true)
    
    }

    
    
    
    @IBAction func insideLoginBtnPress(_ sender: UIButton) {
        
    tapCount += 1
    if tapCount == 5 {
        let insideLoginVC = InsideLoginViewController();
        self.navigationController?.pushViewController(insideLoginVC, animated: true)
        }
        
}

    //登录接口
    func requstLogin(phone:String,password:String) -> Void {
        
        var param : Dictionary<String, String>?
        if (JPUSHService.registrationID() != nil) {
            param =
                [
                    "account": phone,
                    "password":password,
                    "uuid":JPUSHService.registrationID() as String]
        }else {
            param =
                [
                    "account": phone,
                    "password":password,
                ]
        }
        
        Alamofire.request(loginUrl, method:.post, parameters:param)
            .responseString { response in
                switch response.result.isSuccess {
                case true:
                   
                    self.userModel = UserModel.deserialize(from: response.value)
                    if(self.userModel?.status == true) {
                        self.customShowSuccess("登录成功")
                        let share = UserModel.shareUser
                        share.data = self.userModel?.data
                        if ((self.userModel?.data?.user?.count)! > 0){//身份门店列表 选择弹出框
                            let model = self.userModel?.data?.user![0]
                            share.data?.storeId = (model?.sid)!
                            share.data?.roleId = (model?.role_id)!
                            share.data?.workTypeId = (model?.work_id)!
                       
                        UserDefaults.standard.set(share.data?.token, forKey: "Token")
                        
                             let homeVC = HomeTabbarViewController(); self.navigationController?.pushViewController(homeVC, animated: true)
                        }else {//无任何身份 初始用户 去认证
                            if (self.userModel?.data?.certification_status == "0"){//审核中
                                let checkStatusVC = CheckStatusViewController();
                                checkStatusVC.title = "认证中"
                               checkStatusVC.checkStatus = "1"; self.navigationController?.pushViewController(checkStatusVC, animated: true)
                                
                            }else if (self.userModel?.data?.certification_status == "1"){//成功
                                let storeAddVC = StoreAddViewController();
                                storeAddVC.title = "添加店铺"
                                self.navigationController?.pushViewController(storeAddVC, animated: true)
                                
                            }else if (self.userModel?.data?.certification_status == "2"){//失败
                                let checkStatusVC = CheckStatusViewController();
                                checkStatusVC.checkStatus = "0"; checkStatusVC.title = "认证中"
                                self.navigationController?.pushViewController(checkStatusVC, animated: true)
                                
                            }else {//未审核
                                let shopCheckVC = ShopCheckViewController();
                                shopCheckVC.title = "店铺认证"
                                self.navigationController?.pushViewController(shopCheckVC, animated: true)
                            }
                        }
                    }else {
                    self.customShowError((self.userModel?.msg)!)
                    }
                    
                    
                case false:
                    print(response.result.error!)
                    self.customShowError("网络请求错误")
                }
                
                
                
        }
    }
    
    //自动登录
    func requstAutoLogin(token:String) -> Void {

        let headers: HTTPHeaders = [
            "token": token,
//            "Accept": "application/json"
        ]
        
        var param : Dictionary<String, String>?
        if (JPUSHService.registrationID() != nil) {
            param =
                [
                    "uuid":JPUSHService.registrationID() as String
                ]
        }
    Alamofire.request(loginUrl,method:.post,parameters:param, headers:headers) .responseString { response in

            switch response.result.isSuccess {
            case true:
                self.customShowSuccess("登录成功")
                self.userModel = UserModel.deserialize(from: response.value)
                if(self.userModel?.status == true) {
                    print("登录成功");
                    let share = UserModel.shareUser
                    share.data = self.userModel?.data
                UserDefaults.standard.set(share.data?.token, forKey: "Token")

                    if ((self.userModel?.data?.user?.count)! > 0){//身份门店列表 选择弹出框
                        let model = self.userModel?.data?.user![0]
                        share.data?.storeId = (model?.sid)!
                        share.data?.roleId = (model?.role_id)!
                        share.data?.workTypeId = (model?.work_id)!
                        let homeVC = HomeTabbarViewController(); self.navigationController?.pushViewController(homeVC, animated: true)
                    }else {//无任何身份 初始用户 去认证
                        if (self.userModel?.data?.certification_status == "0"){//审核中
                            let checkStatusVC = CheckStatusViewController();
                            checkStatusVC.title = "认证中"
                            checkStatusVC.checkStatus = "1"; self.navigationController?.pushViewController(checkStatusVC, animated: true)

                        }else if (self.userModel?.data?.certification_status == "1"){//成功
                            let storeAddVC = StoreAddViewController();
                            storeAddVC.title = "添加店铺"
                            self.navigationController?.pushViewController(storeAddVC, animated: true)

                        }else if (self.userModel?.data?.certification_status == "2"){//失败
                            let checkStatusVC = CheckStatusViewController();
                            checkStatusVC.checkStatus = "0"; checkStatusVC.title = "认证中"
                            self.navigationController?.pushViewController(checkStatusVC, animated: true)

                        }else {//未审核
                            let shopCheckVC = ShopCheckViewController();
                            shopCheckVC.title = "店铺认证"
                            self.navigationController?.pushViewController(shopCheckVC, animated: true)
                        }
                    }
                }else {
                    self.customShowError((self.userModel?.msg)!)
                }


            case false:
                self.customShowError("网络请求错误")
                print(response.result.error!)
            }



        }
        }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}



